# encoding:utf-8
from flask import render_template, current_app, session, request, jsonify, g
from Info.models import User, News, Category
from Info.module.index import index_blu
from Info.utils.common import user_longin_data
from Info.utils.response_code import RET


@index_blu.route('/news_list')
def get_news_list():
    """
      0、获取数据
      0.1 校验数据
      1、查询出所有新闻 (查询对应分类的新闻)
      2、排序 按照创建时间
      3、分页
    :return:
    """
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return  jsonify(errno = RET.PARAMERR,errmsg = '参数错误')
    # 1、查询出所有新闻(查询对应分类的新闻)
    # 2、排序
    # 按照创建时间
    # 3、分页
    # *args  ()   []  解包
    filters=[News.status==0]
    if cid != 1:
        filters.append(News.category_id == cid)
    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    news_list = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_dict())
    # print(news_list)
    data = {
        'news_dict_li':news_dict_li,
        'current_page':current_page,
        'total_page':total_page
    }
    return  jsonify(errno = RET.OK,errmsg = 'OK',data = data)
@index_blu.route('/')
@user_longin_data
def index():
    """
    显示首页
    1. 如果用户已经登录，将当前登录用户的数据传到模板中，供模板显示
    :return:
    """

    # 二、新闻点击排行功能实现

      # 1、查询出来所有的新闻数据

      # 2、进行排序？？？按点击量排序

      # 3、取出前六条新闻

      # 4、渲染
    user = g.user
    news_list = News.query.order_by(News.clicks.desc()).limit(6).all()
    # 5、将对象列表转化为字典列表
    news_dict_li = []
    for new_obj in news_list:
        # 将新闻对象，变成字典
        news_dict_li.append(new_obj.to_basic_dict())
    # 三、查询分类
    categorys = Category.query.all()
    category_dict_li = []
    # 列表推导式
    # category_dict_li = [category.to_dict() for category in categorys]
    for category in categorys:
        category_dict_li.append(category.to_dict())

    data = {
        "user_info": user.to_dict() if user else None,
        "news_dict_li":news_dict_li,
        "category_dict_li":category_dict_li
    }
    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return  current_app.send_static_file('news/favicon.ico')